﻿using System;
using System.ComponentModel;
using Microsoft.VisualStudio.TestTools.WebTesting;

namespace QA.TFS.Rules.Validation
{

  [Description("Verifies the response URL.  This rule can be used to make sure a redirect to an error page does not occur, for example.")]
  [DisplayName("Validate Response URL")]
  public class ValidateResponseUrl : ValidationRule
  {
    private string _urlStringToFind = String.Empty;
    private bool _failIfFound = true;

    [Description("If true, validation fails if the specified string is found in the response URL.  If false, validation fails if the specified string is not found in the response URL.")]
    public bool FailIfFound
    {
      get { return _failIfFound; }
      set { _failIfFound = value; }
    }

    [Description("The string to search for in the response URL.  For example, enter 'Error.aspx' if you want to make sure the server does not redirect to that error page.")]
    public string UrlStringToFind
    {
      get { return _urlStringToFind; }
      set { _urlStringToFind = value; }
    }

    [Description("Verifies the response URL.  This rule can be used to make sure a redirect to an error page does not occur, for example.")]
    [DisplayName("Validate Response URL")]
    public override void Validate(object sender, ValidationEventArgs e)
    {
      //make sure the string to find has a value
      if (String.IsNullOrEmpty(_urlStringToFind))
      {
        throw new ArgumentException("The UrlStringToFind property cannot be null or empty string.");
      }

      bool found = e.Response.ResponseUri.OriginalString.IndexOf(_urlStringToFind, StringComparison.OrdinalIgnoreCase) != -1;
      string foundMessage = found ? "was" : "was not";

      //set the result message that will appear in the web test viewer details tab and the load test error table
      e.Message = String.Format("The string '{0}' {1} found in the response URL.", _urlStringToFind, foundMessage);

      //set whether the validation passed or failed
      e.IsValid = found != _failIfFound;
    }
  }


}
